Ext.define('UX.codeview.ColumnX', {
	extend : 'Ext.grid.column.Column',
	alias : 'widget.codeviewcolumnx',
	align : 'center',
	sortable : false,
	resizable : false,
	hideable : false,
	menuDisabled : true,
	header: '&#160;',
	actionIdRe: new RegExp(Ext.baseCSSPrefix + 'action-col-(\\d+)'),
	iconCls : 'ux-codeviewx-border', 
	altText: '',
	width : 20,
	
	fieldSearch : false,
	disabledEnter : false,
	defaultPopupConfig : undefined,
	popupColumns : [{
		text : 'Name',
		dataIndex : 'key1',
		disabledSearch : false,
		flex : 1
	}, {
		text : 'Description',
		dataIndex : 'data1',
		disabledSearch : false,
		flex : 2
	}],
	cdvType : 'gcm',
	remoteFilter : true,
	params : {},
	factoryConditionEnabled : true,
	path : '',
	
	constructor : function(configs) {
		var me = this;
		var cfg = Ext.clone(configs||{});
		
		//type : The type of <input> to create: submit, reset or button.
		//cdv 
		var cdvType = cfg.type || this.cdvType || 'gcm';
		cfg.cdvType = cdvType;
		delete cfg.type;
		
		var service = cfg.service ||{};
		if(service.name){
			cfg.serviceUrl = 'service/'+service.name+'.json';
			cfg.path = service.path||'';
			if(!cfg.cdvType){
				cfg.cdvType = 'service';
			}
		}
		if(cfg.columns){
			cfg.popupColumns = cfg.columns;
			delete cfg.columns;
		}
		if(cfg.table){
			delete cfg.tableId;
		}
		
		if(!cfg.popupColumns && cfg.dataIndex){
			me.popupColumns[0].fieldId = cfg.dataIndex;
		}
		
		me.origRenderer = cfg.renderer || me.renderer;
		me.renderer = cfg.renderer = null;
		me.callParent([cfg]);
	},
	defaultRenderer : function(v, meta, record, rowIdx, colIdx, store, view){
		var me = this, prefix = Ext.baseCSSPrefix;
		var scope = me.scope;
		
		var ret = Ext.isFunction(me.origRenderer) ? me.origRenderer.apply(scope, arguments) || '' : '';
		var disabled = me.disabled || (me.isDisabled ? me.isDisabled.call(scope, view, rowIdx, colIdx, me, record) : false);
		var tooltip = disabled ? null : (me.tooltip || (me.getTip ? me.getTip.apply(scope, arguments) : null));
		
		if(me.tableId)
			me.table = me.getTable(record);
		if(!me.serviceUrl && !me.table){
			disabled = true;
		}
		meta.tdCls += ' ' + Ext.baseCSSPrefix + 'action-col-cell';
		
		return  ret +'<img style = "width:20px; height:20px" role="button" alt="' + me.altText + '" src="' + (me.icon || Ext.BLANK_IMAGE_URL) +
        '" class="' + prefix + 'action-col-icon ' + prefix + 'action-col-0 ' + (disabled ? prefix + 'item-disabled' : ' ') +
        ' ' + (Ext.isFunction(me.getClass) ? me.getClass.apply(scope, arguments) : (me.iconCls || '')) + '"' +
        (tooltip ? ' data-qtip="' + tooltip + '"' : '') + ' />';
	},
	getTable : function(record){
		if(this.tableId){
			this.table = record.get(this.tableId);
		}
		return this.table;
	},
	initComponent : function(){
		var me = this;
		me.cdvType = me.cdvType.toLowerCase();
		me.callParent(arguments);
		me.addEvents(
				'beforestoreload',
				'afterstoreload',
				'select',
				'showpopup',
				'closepopup'
		);
		
		me.getBindStore();
	},
	
	processEvent: function(type, view, cell, recordIndex, cellIndex, e, record, row) {
		var me = this,
		match = e.getTarget().className.match(me.actionIdRe);
		if(me.disabled)
			return;
        if(match){
        	if(type == 'click'){
        		me.record = record;
        		
        		if(me.tableId){
        			me.applyParams({
        				table : me.getTable(record)
        			});
                } 
        		if(me.serviceUrl  || me.table){
        			me.showPopup();
        		}
        	}
        }
    },
	
	onBindStoreLoad : function(store, records, success){
		var me = this;
		if(success == false){
			me.popup.close();
			return false;
		}
		
		me.fireEvent('afterstoreload', me, store, records, success);
		
		//me.selectSearchRecord();	
	},
	
	onGridItemClick : function(grid, record, item, index, eOpts){
		var me= this;
		me.setFieldValues(record);
		me.fireEvent('select', me, record);
		me.popup.close();
	},

	onPopupShow : function(popup){
		this.fireEvent('showpopup', this, popup);
	},
	onPopupClose : function(popup){
		this.store.removeAll();
		this.fireEvent('closepopup', this);
	},
	
	bindStoreLoad : function(reload){
		var me = this;
		var store = me.getBindStore();
		var params = Ext.clone(me.params||{});
		if(me.fireEvent('beforestoreload', me, store, params) === false){
			return false;
		}
		store.clearFilter(true);
		store.currentPage=1;
		var proxy = store.getProxy();
		if(params){
			Ext.apply(proxy.extraParams, params);
		}
		if(me.cdvType == 'gcm' || me.cdvType =='table'){
			var proxy = store.getProxy();
			var conditions = me.getCondition(params.condition);
			conditions = me.getSearchConditions(conditions);
			if(conditions.length < 1){
				delete proxy.extraParams.condition;
			}
			else{
				proxy.extraParams.condition = conditions;
			}
			store.load();
		}
		else{
			var filters = me.getSearchFilters()||[];
			if(reload || filters.length < 1){
				store.load();					
			}
			else{
				store.filter(filters);
			}
		}
	},
	
	
	getSearchFilters : function(){
		var me = this;
		var filters = [];
		
		me.searchbar.items.each(function(searchfield) {
			if(!searchfield.isFormField)
				return;
			var value = searchfield.getValue();
			if(value){
				filters.push({
					property : searchfield.getName(),
					value : value
				});				
			}
		}, this);
		return filters;
	},
	getSearchConditions : function(conditions){
		var me = this;
		me.searchbar.items.each(function(searchfield) {
			if(!searchfield.isFormField)
				return;
			var value = searchfield.getValue();
			if (value) {
				conditions.push({
					column : searchfield.getName(),
					value : value + '%',
					operator : 'like'
				});
			}
		}, this);
		return conditions;
	},
	getCondition : function(condition){
		condition = condition || this.condition ||[];
		
		return Ext.clone(condition);
	},
	getSelect : function(){
		var me = this;
		var select = [], selCond = [], columns = me.popupColumns;
		for(var i in columns){
			var col = columns[i];
			if(col.dataIndex){
				select.push(col.dataIndex);
			}
			if (Ext.isEmpty(col.width) && Ext.isEmpty(col.flex)) {
				col.flex = 1;
			}
		}
		
		var cond = me.getCondition();
		if(cond.length>0){
			for(var i in cond){
				if(cond[i].column){
					selCond.push(cond[i].column);
				}
			}
		}
		
		return Ext.Array.merge(select, selCond);
	},
	getRootScope : function(){
		var scope = this.rootScope || this.up('[setKeys]') || this.up('window') || this.up();
		this.rootScope = scope;
		return scope;
	},
	getParams : function(){
		var me = this;
		var store = me.getBindStore();
		var extraParams = Ext.clone(store.proxy.extraParams);
		return extraParams;
	},
	applyParams : function(params){
		var store = this.getBindStore();
		Ext.apply(store.proxy.extraParams, params||{});
	},
	setParams : function(params){
		var me = this;
		var store = me.getBindStore();
		var extraParams = Ext.clone(store.proxy.extraParams);
		if(me.cdvType == 'gcm' || me.cdvType == 'table'){
			extraParams = Ext.apply({
				procstep : '1',
				select : me.getSelect(),
				table : me.table,
				type : me.cdvType
			}, params||{});
		}
		else{
			extraParams = params || {};
		}
		if(me.factoryConditionEnabled === false){
			extraParams.factoryConditionEnabled = false;
		}
		store.proxy.extraParams = extraParams;
	},
	
	setFieldValues : function(record){
		var me = this,
		columns = me.popupColumns||[];
		if(columns.length>0){
			if(me.record){
				var gridRecord = me.record;
				for(var i in columns){
					if(columns[i].fieldId){
						var value = record.get(columns[i].dataIndex);
						gridRecord.set(columns[i].fieldId, value);
					}
				}
			}
		}
	},
	getBindStore : function(){
		return this.store || this.createStore();
	},
	
	createStore : function(){
		// store > url > table 
		var me = this, serviceUrl = '', path = '';
		var params = me.params || {};
		var select = me.getSelect();
		if(me.cdvType == 'gcm' || me.cdvType == 'table'){
			params = Ext.apply({
				procstep : '1',
				select : select,
				table : me.table,
				type : me.cdvType
			}, me.params||{});
			serviceUrl = 'service/basViewCodeList.json';
			path = 'list';
		}
		else if(me.cdvType =='service'){
			serviceUrl = me.serviceUrl;
			path = me.path;
		}
		
		if(me.cdvType == 'memory'){
			store = Ext.create('Ext.data.Store', {
				fields : select
			});
		}
		else{
			store = Ext.create('Ext.data.Store', {
				autoLoad : false,
				fields : select,
				remoteFilter : me.remoteFilter||false,
				pageSize : Ext.isNumber(me.pageSize) ? me.pageSize : (window.CODEVIEW_PAGESIZE || 1000),
				proxy : {
					type : 'payload',
					api : {
						read : serviceUrl
					},
					extraParams : params,
					actionMethods : {
						read : 'POST'
					},
					reader : {
						type : 'json',
						root : path,
						totalProperty : 'total'
					}
				}
			});
		}
		
		store.mon(store, {
			load : me.onBindStoreLoad,
			scope : me
		});
		
		if(me.store){
			me.store.destroyStore();
		}
		me.store = store;
		return store;
	},
	
	showPopup : function(){
		var me = this, popup;
		var grid = me.createGrid();
		var pagebar = me.createPagebar();
		var searchbar = me.createSearchbar();
		popupCfg = Ext.applyIf({
			tools : [ {
				type : 'refresh',
				tooltip : 'Refresh form Data',
				handler : function(event, toolEl, panel) {
					me.bindStoreLoad();
				}
			} ],
			items : [grid, pagebar, searchbar]
		}, me.defaultPopupConfig||{});
		popup = me.popup = Ext.create('UX.codeview.Popup', popupCfg);
		popup.mon(popup, {
			show : me.onPopupShow,
			close : me.onPopupClose,
			scope : me
		});
		
		if(me.bindStoreLoad(!me.fieldSearch) !== false){
			popup.show();
		}
	},
	
	createGrid : function(){
		var me = this;
		var store = me.getBindStore();
		var columns = me.popupColumns || [];
		var grid = me.grid =  Ext.widget({
			xtype : 'grid',
			flex : 1,
			sortableColumns : false,
			enableColumnHide : false,
			enableColumnMove : false,
			columnLines : true,
			store: store,
			columns : columns,
			listeners : {
				itemclick : me.onGridItemClick.bind(me)
			}, 
			tbar : [ {
				width : 30
			},{
				xtype : 'button',
				text : 'Fields Reset',
				handler : function() {
					var record = Ext.ModelManager.create({}, store.model);
					if (record) {
						for ( var i in record.data) {
							record.data[i] = '';
						}
						me.setFieldValues(record);
						me.popup.close();
					}
				}
			} ]
		});
		return grid;
	},
	createPagebar : function(){
		var me = this;
		var store = me.getBindStore();
		var	pagebar = me.pagebar = Ext.widget({
				xtype: 'pagingtoolbar',
		        cls : 'codeviewpagebar',
		        store : store,
		        displayInfo: true,
		        dock: 'bottom',
		        //hidden : true,
		        afterPageText : '/ {0}'
			});
		pagebar.down('#refresh').hide();
		return pagebar;
	},
	createSearchbar : function(){
		var me = this;
		var columns = me.popupColumns;
		var items = [];
		for(var i in columns){
			if(!columns[i].hidden){
				var col = columns[i];
				var value = '';
				if(me.fieldSearch){
					if(col.fieldId){
						if(me.record){
							value = me.record.get(col.fieldId);
						}
					}
				}
				items.push({
					xtype : 'textfield',
					name : col.dataIndex,
					value : value,
					hideLabel : true,
					readOnly : col.disabledSearch || false,
					emptyText : col.text || col.header,
					flex : col.flex,
					listeners : {
						specialkey : function(textfield, e) {
							if (e.getKey() == e.ENTER) {
								me.bindStoreLoad();
							}
						},
						change : function(textfield, val){
							me.grid.getSelectionModel().deselectAll();
						}
					}
				});
			}
		}
		items.push({
			xtype : 'button',
			iconCls : 'ux-codeview-clearBtn navClearBtn',
			margin : '0 0 0 2',
			tooltip : 'Clear Search Fields',
			handler : function(){
				me.searchbar.items.each(function(searchfield) {
					if(!searchfield.isFormField)
						return;
					searchfield.setValue('');
				}, this);
				me.bindStoreLoad();
			}
		});

		var searchbar = me.searchbar = Ext.widget({
			xtype : 'panel',
			height : 39,
			cls : 'windowSearchField',
			layout : {
				align : 'stretch',
				type : 'hbox'
			},
			items : items
		});
		
		return searchbar;
	},
	selectSearchRecord : function(me) {
		me = me||this;
		var grid = me.grid;
		var select = [];
		var selModel = grid.getSelectionModel();
		// 전에 선택된 row에 index 저장
		var beforeIndex = selModel.getLastSelected() ? selModel.getLastSelected().index : -1;
		
		me.searchbar.items.each(function(searchfield) {
			if(!searchfield.isFormField)
				return;
			var name = searchfield.getName() || '';
			var value = searchfield.getValue() || '';

			if (Ext.isEmpty(name) == false && Ext.isEmpty(value) == false) {
				select.push({
					column : searchfield.getName(),
					value : searchfield.getValue()
				});
			}
		});

		
		if(beforeIndex > -1 && !selModel.hasSelection()){
			beforeIndex = -1;
		}
		var pageData = me.pagebar.getPageData();
		var currentPage = pageData.currentPage;
		if(currentPage>1&&beforeIndex>-1){
			beforeIndex = beforeIndex-pageData.fromRecord+1;
		}
		function findBy(record, id) {
			var bMatch = false;

			Ext.Array.each(select, function(item) {
				var value = record.get(item.column);
				var selectValue = item.value;
				
				if (Ext.typeOf(value) == 'string') {
					value = value.toLowerCase();
					selectValue = selectValue.toLowerCase();
					if (value.indexOf(selectValue) > -1) {
						bMatch = true;
					} else {
						bMatch = false;
						return false;
					}
				} else {
					if (value == selectValue) {
						bMatch = true;
					} else {
						bMatch = false;
						return false;
					}
				}
			});
			return bMatch;
		}
		
		var findIndex = grid.store.findBy(findBy, grid.store, beforeIndex+1);
		
		if(findIndex === -1 && beforeIndex !== -1) {
			findIndex = grid.store.findBy(findBy);
		}

		if (findIndex > -1) {
			selModel.select(findIndex);
			//var record = selModel.getLastSelected();
		}
	},
	bindStore : function(store) {
        var me = this,
        oldStore = me.store;

        if(oldStore !=store){
        	oldStore.destroyStore();
            
            me.store = store;

    		if(store){
    			store.mon(store, {
    				load : me.onBindStoreLoad,
    				scope : me
    			});
    		}
        }
	}
});